
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _  = db.command
export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *   "name": "111",
   *   "sort": "11"
   * }
   */
  //1.参数校验
  if (nw.util.isNull(body.name)){
    return fail("分类名称不能为空")
  }
  if (nw.util.isNull(body.sort)){
    body.sort=1
  }
  //2.校验名称是否重复
  let count = await nw.db.count({
    dbName:"category",
    whereJson:{deleted:0,name:_.eq(body.name)}
  })
  if (count>0){
    return fail("分类名称已存在，无法添加")
  }
  //3.构建保存数据
  let data = {
    name:body.name,
    imgUrl:"",
    parentId:"0",
    status:1,
    sort:body.sort,
    createTime:new Date(),
    updateTime:new Date(),
    deleted:0
  }
  //4.保存数据
  let id = await nw.db.add({
    dbName:"category",
    dataJson:data
  })
  if (nw.util.isNull(id)){
    return fail("保存失败")
  }

  return ok("保存成功")



}
